require.config({
    paths: {
        'jquery': ['http://cdn.bootcss.com/jquery/2.2.4/jquery.min', '/js/lib/jquery.min'],
        'doT': '/js/lib/doT.min',
        'bootstrap': '/js/lib/bootstrap.min',
        'datetimepicker': '/js/lib/bootstrap-datetimepicker.min',
        'select2': '/js/lib/select2.min',
        'paginator': '/js/lib/bootstrap-paginator'
    },
    shim: {
        'bootstrap': ['jquery'],
        'paginator': ['bootstrap']
    }
});

var myFun = {
    goodsSum: '',
    goodsInfo: ''
};

require(['jquery', 'doT', 'datetimepicker', 'select2', 'paginator', 'common', 'bootstrap'], function($, doT, datetimepicker, select2, paginator, common) {
    $(function() {
        var isChoose = true;
        var role = sessionStorage.getItem('role');
        var school_id = sessionStorage.getItem('school_id');
        var page_size = 100;

        $('#deliveryInfo').hide();
        //初始化学校列表
        function initSchool() {
            var data;
            $.get(common.urlBase + "/school/allSchool.json", function(data, status) {
                data = eval('(' + data + ')');
                var schools = data.data;
                var schoolTmpl = doT.template($('#template_school').text());
                $('#querySchool').html(schoolTmpl(schools));
                $("#querySchool").select2();
                if (role != 1) {
                    $('#querySchool').attr('disabled', true);
                    $('#querySchool').val(school_id);
                    $('#select2-querySchool-container').text($('#querySchool option[value=' + school_id + ']').text());
                }
            });

            //模拟食堂数据
            // var canteenTmpl = doT.template($('#template_canteen').text());
            // var canteens = [{ 'id': 1, 'name': '一饭' }, { 'id': 2, 'name': '二饭' }]
            // $('#canteens').html(canteenTmpl(canteens));
            // $("#canteens").select2();
        }
        initSchool();

        function initDatetimepicker() {
            var date = new Date();
            //var day = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
            // $('#date').text(day);
            var month = ((date.getMonth() + 1))<10? "0"+(date.getMonth() + 1) : (date.getMonth()+1);
            var oDate = date.getDate()<10? "0"+date.getDate() : date.getDate();
            var day = date.getFullYear() + '-' + month + '-' + oDate;
            $('#date_today').val(day);

            $('.time').datetimepicker({
                format: 'hh:ii',
                autoclose: true,
                startView: 1,
                maxView: 'day',
                minView: 'hour',
                minuteStep: 1,
                title: day
            });
            $('#date_today').datetimepicker({
                format: 'yyyy-mm-dd',
                startView: 2,
                autoclose: true,
                maxView: 'decade',
                minView: 'month',
                endDate: date
            });
            $('#start').val('00:00:00');
            $('#end').val('23:59:59');
        }
        initDatetimepicker();

        $('#delivery').submit(function() {
            var school = $('#querySchool').val();
            var canteen = $('#canteens option:selected').text();
            var status = $('#status').val();
            var start_time = Date.parse($('#date_today').val() + ' ' + $('#start').val());
            var end_time = Date.parse($('#date_today').val() + ' ' + $('#end').val());
            page_size = $('#page_size').val();

            if (start_time > end_time) {
                $('#tips').text('请选择正确的时间!');
                return false;
            } else {
                $('#tips').text('');
            }

            myFun.data = {
                'status': status,
                'school_id': school,
                'start_time': start_time,
                'end_time': end_time
            };

            refreshDelivery(1);

            //换日期,初始化进度条
           $("#date_today").on("change",function() {
              $("#queryGoods").click(function() {
                  $(".success-num").html("0%");
                  $("#sendResult").html("");
                  $(".progress-bar").css("width",0+"%");
                  $(".success-num").css("left",2+"%");
              })
           });

             //判断日期不是当日禁发送按钮
            var date = new Date();
            var month = ((date.getMonth() + 1))<10? "0" + (date.getMonth() + 1) : (date.getMonth()+1);
            var oDate = date.getDate()<10? "0" + date.getDate() : date.getDate();
            var day = date.getFullYear() + '-' + month + '-' + oDate;
            if(($("#date_today").val()) == day) {
               $("#pullOrder").prop("disabled", false);

            }else{
                $("#pullOrder").prop("disabled", true);
            }


            //获取openID

               var schoolId = sessionStorage.getItem("school_id");
               if(role==1){
                   schoolId = school;
               }
                $.get(common.urlBase + '/sender/getopenid.json?school_id=' + schoolId, function(_d) {
                    if(_d.data && _d.data.obj){
                        var openids = JSON.stringify(_d.data.obj).replace(/\"/g, "");
                        var openidsNum = _d.data.obj.length;
                        myFun.sendOrder && myFun.sendOrder(openids,openidsNum)
                    }

                }, "json");

            return false;
        });

        myFun.sendOrder = function (d,_openidsNum) {
            //获得选中
             $("#pullOrder").on("click",function() {
                var ordersArr = [];   //用来保存每条数据
                var successNum = 0;
                var $ordersIndex = $(".ordersIndex").find("input");
                $ordersIndex.each(function() {
                    if($(this).prop("checked")){
                        var _this = $(this);
                        var $tdSiblings =_this.closest("td");
                        var rowspanNum = Number($tdSiblings.attr("rowspan"));
                        var remark;
                        var _delivers = [];
                        var deliverItem = {};
                        var tradeID = $tdSiblings.data("tradeid");
                        //remarkd 的两种情况
                        //多点
                        if( rowspanNum > 1){
                            deliverItem.item_name = getInfo(".itemName");
                            deliverItem.item_num = getInfo(".itemCount");
                            _delivers.push(deliverItem);
                           remark = getInfo(".itemName")+getInfo(".itemCount")+"份";
                           var $moreOrders = "."+($tdSiblings.data("tradeid"));  //通过tradeId找到多点的
                           var len = $($moreOrders).length;

                           for(var i=0; i<len; i++){
                              var count = $($moreOrders).siblings(".moreOrderCount").html();
                              remark +=","+$($moreOrders).eq(i).html()+count+"份";
                              var deliverItem1 = {};
                               deliverItem1.item_name = $($moreOrders).eq(i).html();
                               deliverItem1.item_num = count;
                               _delivers.push(deliverItem1);
                            }

                        //单点
                        }else{
                            remark = getInfo(".itemName")+getInfo(".itemCount")+"份";
                            deliverItem.item_name = getInfo(".itemName");
                            deliverItem.item_num = getInfo(".itemCount");
                            _delivers.push(deliverItem);
                        }

                       function getInfo(info){
                            return $tdSiblings.siblings(info).html();
                        }

                        var tradeTime = getInfo(".tradeTime");
                        var receiverName = getInfo(".receiverName");
                        var receiverAddress = getInfo(".receiverAddress");
                        var customerInfo = receiverName+","+receiverAddress;
                        var customerTel = getInfo(".receiverTel");
                        var sendStatus = getInfo(".send_status");
                        var _message = getInfo(".message")==null?"":getInfo(".message");
                        var tradejson = {
                            trade_id:tradeID,
                            delivers:_delivers,
                            message:_message,
                            name:receiverName,
                            address:receiverAddress,
                            mobile: customerTel,
                            status: sendStatus,
                            create_time: tradeTime
                        };
                        var _data_str = {
                            "first": {"value": "你有我校食堂的新定单","color": "#173177"},
                            "tradeDateTime": {"value": tradeTime,"color": "#173177"},
                            "orderType": {"value": "配送订单","color": "#173177"},
                            "customerInfo": {"value": customerInfo,"color": "#173177"},
                            "orderItemName": {"value": "电话","color": "#000"},
                            "orderItemData": {"value": customerTel,"color": "#173177"},
                            "remark": {"value": remark}
                        };
                        //用来套模板消息的数据
                        var singleData = {
                            //d
                            //oT4UAxNYXLQlYNYmIb3n_87aa2gs
                               openids: d,
                              data_str: JSON.stringify(_data_str),
                           template_id: "qn8khetF62N5aMQ3MN3SuwrNadXKdKx3Pl6HQRahOQU",
                                   url: "http://pushi2016.com/packer/wx/get_order?tradejson="+JSON.stringify(tradejson),
                                 tids:"["+tradeID+"]"
                        };
                        ordersArr.push(singleData);//push 入 orderArr
                    }
                });

                //提示框

                var ordersNum = ordersArr.length;
                if(!ordersNum) {
                    $('#sendMsg').text("请先选择订单！");
                    $('#sendModal').modal({
                        backdrop:"static"
                    });
                    $("#sendConfirm").one("click", function() {
                        $('#sendModal').modal('hide');
                    })
                }else if (!_openidsNum){
                    $('#sendMsg').text("还没有配送员");
                    $('#sendModal').modal({
                        backdrop:"static"
                    });
                    $("#sendConfirm").one("click", function() {
                        $('#sendModal').modal('hide');
                    })
                }else{
                    $('#sendMsg').text("将这"+ordersNum+"条订单发送给"+_openidsNum+"位配送员？");
                    $('#sendModal').modal({
                        backdrop:"static"
                    });

                    $("#sendConfirm").off("click").one("click", function() {
                        sendOrders();
                        $("#sendModal").modal('hide');
                    });
                }

                //发送抢单数据;

                 function sendOrders() {
                     for(var i=0; i<ordersArr.length; i++){
                         $.ajax({
                             url: common.urlBase + '/wx/send_template',
                             method: "post",
                             data: ordersArr[i],
                             success: function(data) {
                                 if(data.ok) {
                                         successNum++;
                                 }
                                 successSendShow && successSendShow(successNum);
                             },
                             error:function(){
                                 console.log("error");
                             },
                             dataType: "json"
                         })
                     }
                 }

             // 进度条
               function successSendShow(_successNum) {
                  var succssSendNum = _successNum;
                  var ordersIndexLen = ordersNum;
                  var persent = (succssSendNum/ordersIndexLen)*100;
                  var progressPersent = persent + "%";
                  var progressTpl = doT.template($("#template_progress").text());
                  //var $successNum = $(".success-num");
                   $("#sendBar").html(progressTpl(progressPersent));
                   if(persent == 100) {
                       $("#sendResult").html("订单已全部发送成功，总数:"+ordersNum+"条");
                       $(".success-num").html("100%");
                       $(".success-num").css("left",(persent-7)+"%");
                       $('#delivery').trigger("submit");
                   }else if(persent == 0) {
                       $(".success-num").html("0%");
                   }else{
                       $(".success-num").html(parseInt((succssSendNum/ordersIndexLen)*100)+"%");
                       $(".success-num").css("left",persent+"%");
                       $("#sendResult").html("已成功发送"+successNum+"条订单,总数:"+ordersNum+"条");
                   }
               }

            })
        };





        $('#export_goodsSum').on('click', function() {
            if (myFun.goodsSum) {
                var title = ['商品', '数量'];
                var titleForKey = ['item_name', 'count'];

                exportTable({
                    title: title,
                    titleForKey: titleForKey,
                    data: myFun.goodsSum.data,
                    file_name: '商品数量.csv',
                    type: 'goodsSum'
                });
            } else {
                $('#noticeMsg').text('无相关信息');
                $('#noticeModal').modal('show');
            }
        });

        $('#export_goodsInfo').on('click', function() {
            if (myFun.goodsInfo) {
                var created_time = $('#created_time').is(':checked');
                var status = $('#status_check').is(':checked');
                var title = ['商品', '数量', '收货人', '地址', '留言', '电话'];
                var titleForKey = ['item_name', 'count', 'receiver_name', 'receiver_address', 'message', 'receiver_mobile'];

                if (status) {
                    title.push('状态');
                    titleForKey.push('status');
                }
                if (created_time) {
                    title.push('交易创建时间');
                    titleForKey.push('created_time');
                }

                exportTable({
                    title: title,
                    titleForKey: titleForKey,
                    data: myFun.goodsInfo.data,
                    file_name: '商品详情.csv',
                    type: 'goodsInfo',
                    created_time: created_time,
                    status: status
                });
            } else {
                $('#noticeMsg').text('无相关信息');
                $('#noticeModal').modal('show');
            }


        });

        function getGoodsInfo(page, page_size) {
            var goodsInfoTmpl = doT.template($('#template_goodsInfo').text());
            myFun.data.page_no = page;
            myFun.data.page_size = page_size;

            //获取订单详情
            $.post(common.urlBase + '/deliver/youzandeliver/get', myFun.data, function(data, statu) {
                data = $.parseJSON(data);
                if (data.data.total_result) {
                    var total = data.data.total_result;
                    var pageNumber = Math.ceil(total / page_size);
                    $('#total').text(total);
                    myFun.goodsInfo = data;
                    $('#goodsInfo').html(goodsInfoTmpl(data.data.obj));
                    initPaginator(page, 8, pageNumber);
                    $('#deliveryInfo').show();
                    $(".sendStatus").each(function() {
                        if($(this).html() == "已送达") {
                            var $siblings = $(this).siblings(".ordersIndex");
                             $(this).closest("tr").css("background","#eee");
                            var $choosed =  $siblings.data("tradeid");
                            $("."+$choosed).closest("tr").css("background","#eee");
                            $siblings.find("input[type=\"checkbox\"]").prop("disabled",true);
                            $siblings.find("label").css("cursor","default");
                        }
                    });

                    if($("#getAll").prop("checked")){
                        $("#getAll").prop("checked",false)
                    }
                    isChoose = true;

                } else {
                    myFun.goodsInfo = '';
                    $('#noticeMsg').text('无相关信息');
                    $('#noticeModal').modal('show');
                    $('#deliveryInfo').hide();
                }
            });
        }

        function getGoodsSum(page, page_size) {
            var goodsSumTmpl = doT.template($('#template_goodsSum').text());
            myFun.data.page_no = page;
            myFun.data.page_size = page_size;

            $.post(common.urlBase + '/deliver/youzancanteen/get', myFun.data, function(data, statu) {
                data = eval('(' + data + ')');
                if (data.data.total_result) {
                    myFun.goodsSum = data;
                    $('#goodsSum').html(goodsSumTmpl(data.data.obj));
                    var goods_count = 0;
                    $.each(data.data.obj, function() {
                        goods_count += this.count;
                    });
                    myFun.goods_count = goods_count;
                    $('#goods_count').text(goods_count);
                    $('#deliveryInfo').show();
                } else {
                    myFun.goodsSum = '';
                    $('#noticeMsg').text('无相关信息');
                    $('#noticeModal').modal('show');
                    $('#deliveryInfo').hide();
                }
            });
        }

        function exportTable(obj) {
            var title = obj.title;
            var titleForKey = obj.titleForKey;
            var data = obj.data.obj;
            var str = [];
            str.push(title.join(',') + '\n');
            if (obj.type == 'goodsSum') {
                for (var i = 0; i < data.length; i++) {
                    var temp = [];
                    for (var j = 0; j < titleForKey.length; j++) {
                        temp.push(data[i][titleForKey[j]]);
                    }
                    str.push(temp.join(',') + '\n');
                }
                var sum = ['总数', myFun.goods_count];
                str.push(sum.join(',') + '\n');
            } else {
                for (var i = 0; i < data.length; i++) {
                    for (var k = 0; k < data[i]['delivers'].length; k++) {
                        var temp = [];
                        for (var j = 0; j < titleForKey.length; j++) {
                            switch (titleForKey[j]) {
                                case ('created_time'):
                                case ('status'):
                                    {
                                        if (obj[titleForKey[j]]) {
                                            temp.push(data[i][titleForKey[j]]);
                                        }
                                    }
                                    break;
                                case ('message'):
                                    {
                                        temp.push(data[i]['message']);
                                    }
                                    break;
                                default:
                                    temp.push(data[i]['delivers'][k][titleForKey[j]]);
                            }
                        }
                        str.push(temp.join(',') + '\n');
                    }
                }
            }

            var uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str.join(""));
            var downloadLink = document.createElement("a");
            downloadLink.href = uri;
            downloadLink.download = obj.file_name;
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
        }

        function refreshDelivery(page) {
            getGoodsSum(page, page_size);
            getGoodsInfo(page, page_size);
        }

        function initPaginator(currentPage, numberOfPages, totalPages) {
            var options = {
                currentPage: currentPage,
                numberOfPages: numberOfPages,
                totalPages: totalPages,
                itemTexts: function(type, page, current) {
                    switch (type) {
                        case 'first':
                            return '首页';
                        case 'prev':
                            return '上一页';
                        case 'next':
                            return '下一页';
                        case 'last':
                            return '末页';
                        case 'page':
                            return page;

                    }
                },
                onPageChanged: function(event, oldPage, newPage) {
                    refreshDelivery(newPage);
                }
            };
            $('#paginator').bootstrapPaginator(options);
        }
      // 全选

      myFun.getAll = function() {
          var $ordersIndex = $(".ordersIndex").find("input");
          if (isChoose) {

              $ordersIndex.each(function () {
                  if (!$(this).prop("disabled")) {

                      $(this).prop("checked", true)

                  }
              });
          } else {
              $ordersIndex.prop("checked", false)
          }
          isChoose = !isChoose;
      };



    });
});




